/**
 * 
 */
package com.qdairlines.service.wx.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.qdairlines.common.IpUtil;
import com.qdairlines.common.TimeUtil;
import com.qdairlines.dao.log.LogMapper;
import com.qdairlines.entity.log.WxSendLog;
import com.qdairlines.entity.wx.WxUserMsg;
import com.qdairlines.service.mq.send.SendQService;
import com.qdairlines.service.wx.wxService;

/**
 * @author pangyannan
 * @date 2017年6月6日
 * @company QingDao Airlines
 * @description
 */
@Service
public class wxServiceImpl implements wxService{
	@Autowired
	private SendQService sendQService;

	@Autowired
	private LogMapper logMapper;

	@Override
	public void sendMsg(WxUserMsg wxUserMsg) {
		//设置sysName为本机名@IP
		wxUserMsg.setSysName(IpUtil.getLocalHost());
		
		//设置消息过期时间
		String validTime = wxUserMsg.getValidTime();
		if(StringUtils.isEmpty(validTime) ||
				!TimeUtil.isValidDateyyyyMMddHHmmss(validTime) ||
				!TimeUtil.isValidDateyyyyMMdd(validTime)
				){
			//如果有效期没有或者格式错误，则默认为当前时间+1天
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			Calendar c = Calendar.getInstance();
			c.add(Calendar.DAY_OF_MONTH, 1);
			validTime = df.format(c.getTime());
		}
		Gson gson = new Gson();
		sendQService.sendMsgWx(gson.toJson(wxUserMsg));
		this.saveSendMsgLog(wxUserMsg);
	}



	@Override
	public void SendMsg(String workcode, String content) {
		WxUserMsg wxUserMsg = new WxUserMsg();
		wxUserMsg.setWorkcode(workcode);
		wxUserMsg.setContent(content);
		
		this.sendMsg(wxUserMsg);
		
	}


	@Override
	public void saveSendMsgLog(WxUserMsg wxUserMsg) {
		WxSendLog wxSendLog = new WxSendLog();
		wxSendLog.setCreateTime(new Date());
		wxSendLog.setSysName(wxUserMsg.getSysName());
		wxSendLog.setWorkcode(wxUserMsg.getWorkcode());
		wxSendLog.setContent(wxUserMsg.getContent());
		wxSendLog.setValidTime(wxUserMsg.getValidTime());
		logMapper.recordWxSendLog(wxSendLog);
	}	
}
